package com.wzy.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wzy.domain.entity.Article;
import com.wzy.domain.entity.Collection;
import com.wzy.domain.vo.ArticleListVO;
import com.wzy.mapper.ArticleMapper;
import com.wzy.mapper.CollectionMapper;
import com.wzy.util.ArticleUtils;
import com.wzy.util.BeanCopyUtils;
import com.wzy.util.RedisCache;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.function.Function;

import static com.wzy.constant.RedisConstants.ARTICLE_Z_SET_KEY;
import static com.wzy.constant.RedisConstants.REDIS_ARTICLE_VIEW_KEY;
import static com.wzy.constant.SystemConstants.PASS;
import static com.wzy.constant.SystemConstants.RELEASE;

/**
 * 文章通用方法
 *
 * @author ultima
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class ArticleCommonService
{
    private final ArticleMapper articleMapper;
    private final CategoryService categoryService;
    private final RedisCache redisCache;
    private final CollectionMapper collectionMapper;

    /**
     * 初始化Redis文章列表
     */
    public void redisArticleList()
    {
        List<Article> articles = articleMapper.selectList(new LambdaQueryWrapper<Article>()
                .eq(Article::getArticleStatus, RELEASE)
                .eq(Article::getArticleExamine, PASS));
        // 查询 categoryName
        articles.forEach(article -> article.setCategoryName(((Function<Article, String>) article1 -> {
            Long id = article1.getCategoryId();
            return categoryService.getById(id).getName();
        }).apply(article)));

        List<ArticleListVO> articleListVOS = BeanCopyUtils.copyBeanList(articles, ArticleListVO.class);
        redisCache.deleteObject(ARTICLE_Z_SET_KEY);
        // 从 redis中获取浏览量
        articleListVOS.forEach(articleListVO ->
        {
            String redisKey = REDIS_ARTICLE_VIEW_KEY + articleListVO.getId().toString();
            articleListVO.setViewCount(Long.valueOf(redisCache.getCacheObject(redisKey).toString()));
            Collection collection = collectionMapper.selectOne(new QueryWrapper<Collection>()
                    .eq("article_id", articleListVO.getId())
                    .select("COUNT(1) AS collection_count"));
            redisCache.setZSet(ARTICLE_Z_SET_KEY, articleListVO,
                    ArticleUtils.getArticleScore(articleListVO.getViewCount(), 0L, collection.getCollectionCount()));
        });
    }

}
